﻿var GetAttchListUrl = "system/common/attach/list"
var UploadAttachUrl = "system/common/attach/upload"
var UploadChunkAttachUrl = GetApiPath() + "system/common/attach/uploadChunkFile"
var DeleteAttachUrl = "system/common/attach/delete"
var ReadAttachUrl = GetApiPath() + "system/common/attach/download"
$(function() {

})

function BindAttach(GroupGuid) {
    var cloudUploadList = $("boot-upload");
    for (var i = 0; i < cloudUploadList.length; i++) {
        var cloudUpload = cloudUploadList[i];
        var id = $(cloudUpload).attr("id");
        if (!id) {
            id = GetNewGuid();
        }
        var cloudUploadtBtnID = "cloudUploadBtnID_" + id;
        var cloudUploadFileID = "cloudUploadFileID_" + id;
        var cloudUploadTipID = "cloudUploadTipID_" + id;
        var cloudUploaFileListID = "cloudUploaFileListID_" + id;
        var cloudProgressID = "cloudProgressID_" + id;
        var GroupType = $(cloudUpload).attr("grouptype");
        var text = "";
        text += "  <div id=\"fileupload\" class=\"cloud-upload-container\">";
        text += "            <button class=\"layui-btn layui-btn-sm  uploadbtn\" type=\"button\" id=" + cloudUploadtBtnID + "><span class=\"btntext\"><i class=\"layui-icon layui-icon-upload\"></i><span class=\"searchtext\">选择文件</span></span></button>";
        text += "            <input style=\"display:none\"  class='uploadfile' type=\"file\" id=" + cloudUploadFileID + " groupguid='" + GroupGuid + "' grouptype='" + GroupType + "' />";
        text += "            <div class=\"cloud-upload-errorinfo\" id=" + cloudUploadTipID + " style='display:none'>";
        text += "                <span style=\"font-size:14px;color:red\"></span>";
        text += "            </div>";
        text += "           <div class=\"layui-progress\" style='margin-top:5px;display:none' lay-filter='" + cloudProgressID + "' id='" + cloudProgressID + "' >";
        text += "               <div class=\"layui-progress-bar\" lay-percent=\"0%\"></div>";
        text += "            </div>";
        text += "            <div class=\"cloud-upload-filelist\" id=" + cloudUploaFileListID + ">";
        text += "            </div>";
        text += "        </div>";
        cloudUpload.innerHTML = text;
        BindCloudAttach(GroupGuid, GroupType, cloudUploaFileListID);
        layui.element.render("progress")
    }
    $(".uploadbtn").each(function() {
        $(this).click(function() {
            var cloudUploadFileID = "cloudUploadFileID_" + $(this).attr("id").split("_")[1];
            $("#" + cloudUploadFileID).click();
        })
    })
    $(".uploadfile").each(function() {
        var GroupGuid = $(this).attr("groupguid");
        var GroupType = $(this).attr("grouptype");
        $(this).change(function() {
            var cloudUploadFileID = "cloudUploadFileID_" + $(this).attr("id").split("_")[1];
            var cloudUploaFileListID = "cloudUploaFileListID_" + $(this).attr("id").split("_")[1];
            var fileUpload = $("#" + cloudUploadFileID).get(0);
            var files = fileUpload.files;

            var chunkSize = GetProjectConfigValue("fileChunkSize") * 1024 * 1024;
            var file = files[0];

            if (file.size > chunkSize) {
                //分片上传
                var filesize = file.size;
                var filename = file.name;
                var chunkCount = Math.ceil(filesize / chunkSize);
                CreateSimpleFileMD5(file, chunkSize, function(fileMD5) {
                    console.log("计算文件MD：" + fileMD5);
                    $("#" + cloudProgressID).show();
                    var worker = new Worker(GetRootPath() + 'plugins/upload/worker.js');
                    var param = {
                        token: GetTokenID(),
                        attachGuid: GetNewGuid(),
                        uploadUrl: UploadChunkAttachUrl,
                        filename: filename,
                        filesize: filesize,
                        fileMD5: fileMD5,
                        groupguid: GroupGuid,
                        grouptype: GroupType,
                        chunkCount: chunkCount,
                        chunkSize: chunkSize,
                        file: file
                    }
                    worker.onmessage = function(event) {
                        var workresult = event.data;
                        if (workresult.code == 0) {
                            //更新进度
                            layui.element.progress(cloudProgressID, workresult.percent + "%")
                            if (workresult.percent == 100) {
                                $("#" + cloudProgressID).hide();
                                $("#" + cloudUploadFileID).val('');
                                BindCloudAttach(GroupGuid, GroupType, cloudUploaFileListID);
                                worker.terminate();
                            }
                        } else {
                            $("#" + cloudProgressID).hide();
                            $("#" + cloudUploadFileID).val('');
                            worker.terminate();
                        }

                    }
                    worker.postMessage(param);
                })
            } else {
                var formData = new FormData();
                formData.append("file", file);
                formData.append("group_guid", GroupGuid);
                formData.append("group_type", GroupType);
                HttpForm(formData, UploadAttachUrl, function(res) {
                    if (res.code == 0) {
                        BindCloudAttach(GroupGuid, GroupType, cloudUploaFileListID);
                    } else {
                        OpenFail(res.data);
                    }
                })
                $("#" + cloudUploadFileID).val('');
            }
        })
    })
}

function DisableAttachControl() {
    $(".uploadbtn").remove();
    $(".layui-icon-delete").remove();
}

function BindCloudAttach(GroupGuid, GroupType, FileListID) {
    if (GroupGuid != "") {
        var param = { "group_guid": GroupGuid, "group_type": GroupType }
        HttpPost(JSON.stringify(param), GetAttchListUrl, function(res) {
            if (res.code == 0) {
                var text = "";
                $(res.data.obj).each(function() {
                    text += "                <div class=\"cloud-upload-fileitem\">";
                    text += "                    <i style=\"font-size:14px;cursor:pointer;margin-right:5px\" class=\"layui-icon  layui-icon-file\"></i>";
                    text += "                    <span style=\"font-size:14px;cursor:pointer\" onclick=ReadCloudAttach('" + this.row_id + "')>" + this.attach_name + "</span>";
                    text += "                    <i style=\"font-size:14px;cursor:pointer;margin-left:10px\" class=\"layui-icon layui-icon-delete\"  onclick=DeleteCloudAttach('" + this.row_id + "','" + GroupGuid + "','" + GroupType + "','" + FileListID + "')></i>";
                    text += "                </div>";
                })
                $("#" + FileListID).html(text);
            }
        })
    }

}

function DeleteCloudAttach(AttachGuid, GroupGuid, GroupType, FileListID) {
    OpenConfirm('确认删除该文件？', function() {
        var param = { "row_id": AttachGuid }
        HttpPost(JSON.stringify(param), DeleteAttachUrl, function(res) {
            if (res.code == 0) {
                BindCloudAttach(GroupGuid, GroupType, FileListID);
            }
        })
    })
}

function ReadCloudAttach(AttachGuid) {
    var url = ReadAttachUrl + "?row_id=" + AttachGuid;
    window.top.open(url);
}

function CreateSimpleFileMD5(file, chunkSize, finishCaculate) {
    var fileReader = new FileReader();
    var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
    var chunks = Math.ceil(file.size / chunkSize);
    var currentChunk = 0;
    var spark = new SparkMD5.ArrayBuffer();
    var startTime = new Date().getTime();
    loadNext();
    fileReader.onload = function() {
        spark.append(this.result);
        if (currentChunk == 0) {
            currentChunk = chunks - 1;
            loadNext();
        } else {
            var fileMD5 = BootMD5(spark.end() + file.lastModifiedDate);
            finishCaculate(fileMD5)
        }
    };

    function loadNext() {
        var start = currentChunk * chunkSize;
        var end = start + chunkSize >= file.size ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    }
}